package com.xpert.controller;

import java.io.IOException;
import java.util.*;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xpert.action.CommandAction;

public class ActionController extends HttpServlet {
    private static final long serialVersionUID = -1069918205928746610L;
    private Map<String, Object> commandMap = new HashMap<String, Object>(); //명령어와 명령어 처리 클래스를 key, value 쌍으로 저장

    /*
     * @see javax.servlet.GenericServlet#init()
     *-------------------------------------------- 
     * public void init() throws ServletException
     *-------------------------------------------- 
     * A convenience method which can be overridden so that there's no need to
     * call super.init(config).
     *
     * Instead of overriding init(ServletConfig), simply override this method
     * and it will be called by GenericServlet.init(ServletConfig config). The
     * ServletConfig object can still be retrieved via getServletConfig().
     *
     *-----------------------------------------------------------------
     * public void init(ServletConfig config)throws ServletException
     *-----------------------------------------------------------------
     ***** Called by the servlet container to indicate to a servlet that ******
     ***** the servlet is being placed into service. ******
     *
     * See Servlet#init. This implementation stores the ServletConfig object
     * it receives from the servlet container for later use. When overriding
     * this form of the method, call super.init(config).
     * 
     */
    public void init() throws ServletException {
    	loadProperties("com/xpert/properties/Command");			// uri = Action Class
    }
    
    private void loadProperties(String path) {
    	//properties 설정을 읽어 rbHome에 저장
    	ResourceBundle rbHome = ResourceBundle.getBundle(path); 	
    	Enumeration<String> actionEnumHome = rbHome.getKeys();		// key값들, 즉 url 리스트 저장
    	
    	while (actionEnumHome.hasMoreElements()) {
        String command = actionEnumHome.nextElement();
        String className = rbHome.getString(command);		// 개개의 key값(command)으로 value(full class name)를 리턴받는다
    
        try {
      		Class<?> commandClass = Class.forName(className); 	//클래스명으로 클래스를 생성
      		Object commandInstance = commandClass.newInstance(); 	// 생성된 클래스의 인스턴스 생성
      		this.commandMap.put(command, commandInstance); 		// Map에 command명(*.do)과 인스턴스(XxxAction) 저장
        }
        catch (ClassNotFoundException e) {
        	continue;
        } catch (InstantiationException e) {
        	e.printStackTrace();
        } catch (IllegalAccessException e) {
        	e.printStackTrace();
        }

    	}
    }

    //get, post 방식 모두 requestPro로 처리
    public void doGet(HttpServletRequest request,
	    HttpServletResponse response) throws ServletException, IOException {
    	requestProc(request, response);
    }
    //get, post 방식 모두 requestPro로 처리
    protected void doPost(HttpServletRequest request,
	    HttpServletResponse response) throws ServletException, IOException {
    	requestProc(request, response);
    }

    // 사용자 요청을 분석해서 해당 작업 처리
    public void requestProc(HttpServletRequest request, 
	    HttpServletResponse response) throws ServletException, IOException {
    	String view = null;
    	CommandAction com = null;
    	
    	try {
  	    String command = request.getRequestURI();
  	    if(command.indexOf(request.getContextPath()) == 0) {
  	    	command = command.substring(request.getContextPath().length());
  	    }
  
  	    com = (CommandAction) this.commandMap.get(command);
  	    if(com == null) {
      		System.out.println("not found : " + command);
      		return;
  	    }
  
  	    view = com.requestProc(request, response);
  	    if(view == null) {
      		return;
  	    }
    	    
    	} catch (Throwable e) {
    	    throw new ServletException(e);
    	}
	/*
	if(view == null)
	    return;
	*/
	RequestDispatcher dispatcher = request.getRequestDispatcher(view);
		dispatcher.forward(request, response);
  }
    
}
